package com.example.j202411.views.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;


import com.example.j202411.adapter.BooksAdapter;
import com.example.j202411.contract.BooksContact;
import com.example.j202411.databinding.ActivityBooksBinding;
import com.example.j202411.Model.Books;
import com.example.j202411.viewmodel.BooksModel;

import java.util.ArrayList;
import java.util.List;

public class BooksActivity extends AppCompatActivity implements BooksContact.BooksView {
    private ActivityBooksBinding binding ;
    private BooksAdapter adapter ;
    private List<Books.ResultData.BookData> bookDataList ;
    private BooksContact.BooksPresenter presenter ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBooksBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }
    private void init() {
        presenter = new BooksModel(this, this);
        Intent intent = getIntent();
        if (intent == null) {
            Log.e("books00000000000000", "Intent is null");
            return;
        }
        String catalog_id = intent.getStringExtra("catalog_id");
        if (catalog_id == null) {
            Log.e("books00000000000000", "catalog_id is null");
            // 处理 catalog_id 为 null 的情况，例如显示错误提示或返回上一个页面
            Toast.makeText(this, "Catalog ID not found", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        Log.d("books00000000000000", "catalog_id: " + catalog_id);

        try {
            int catalogIdInt = Integer.parseInt(catalog_id);
            presenter.getData(catalogIdInt);
        } catch (NumberFormatException e) {
            Log.e("books00000000000000", "Invalid catalog_id format: " + catalog_id, e);
            Toast.makeText(this, "Invalid Catalog ID format", Toast.LENGTH_SHORT).show();
            finish();
        }

        bookDataList = new ArrayList<>();
        adapter = new BooksAdapter(bookDataList, this);
        binding.recyclerViewBooks.setLayoutManager(new GridLayoutManager(this, 2));
        binding.recyclerViewBooks.setAdapter(adapter);
    }

    @Override
    public void showData(Books books) {
        bookDataList =books.getResult().getData();
        adapter.updateData(bookDataList);
    }

}